package com.koron.operation.census.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.koron.bean.base.Response;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.operation.census.bean.*;
import com.koron.operation.census.mapper.IntactRateBeanMapper;
import com.koron.operation.census.services.IntactRatioService;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Author: rocky
 * @Date: 2022/2/22 11:39
 */
@Api(tags = "运行统计")
@RestController
@Slf4j
@RequestMapping("/intactratio")
public class IntactRatioController {

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    @Autowired
    private IntactRatioService intactratioservice;

    @ApiOperation(value = "机组完好率详情表")
    @PostMapping("/intactRatioDetails")
    public Response<List> intactRatioDetails(@RequestBody IntactRatioDto dto) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), intactratioservice, "intactRatioDetails", List.class, dto));
    }

    @ApiOperation(value = "机组运行台时")
    @PostMapping("/unitRunTime")
    public Response<List<UnitRunTimeVo>> unitRunTime(@RequestParam("beginDay") Date beginDay, @RequestParam("endDay") Date endDay) {
        Assert.isFalse(ObjectUtil.isEmpty(beginDay), "开始时间不能为空");
        Assert.isFalse(ObjectUtil.isEmpty(endDay), "结束时间不能为空");
        return Response.ok(ADOConnection.runTask(getCurrDs(), intactratioservice, "unitRunTime", List.class, beginDay, endDay));
    }

    @ApiOperation(value = "机组检修台时")
    @PostMapping("/unitOverhaulTime")
    public Response<List<OverhaulTimeVo>> unitOverhaulTime(@RequestParam("beginDay") Date beginDay, @RequestParam("endDay") Date endDay) {
        Assert.isFalse(ObjectUtil.isEmpty(beginDay), "开始时间不能为空");
        Assert.isFalse(ObjectUtil.isEmpty(endDay), "结束时间不能为空");
        return Response.ok(ADOConnection.runTask(getCurrDs(), intactratioservice, "unitOverhaulTime", List.class, beginDay, endDay));
    }


//    @ApiOperation(value = "风控系统设备完好率冗余-定时任务")
    @XxlJob(value = "intactRateredundancy")
    @GetMapping("/intactRateredundancy")
    public String intactRateredundancy() {
//        String dbstr = XxlJobHelper.getJobParam();//任务参数 数据库标识
        String dbstr = "water_02";
        ADOConnection.runTask(dbstr, factory -> {
            previousyears(factory, dbstr);//往年统计
            halfayear(factory, dbstr);//半年统计

            return true;
        }, Boolean.class);

        return null;
    }

    // 往年平均设备完好率
    private void previousyears(SessionFactory factory, String dbstr) {
        IntactRateBeanMapper mapper = factory.getMapper(IntactRateBeanMapper.class);
        DateTime dateTime = DateUtil.offsetMonth(new Date(), -12);
        int yesteryear = DateUtil.year(dateTime);
        //查往年的 一整年的 月平均设备完好率
        List<IntactRateBean> intactRatelist = mapper.queryByYearAndQuarter(yesteryear, 4);
        if (CollUtil.isEmpty(intactRatelist)) {
            String endtimeStr = StrUtil.format("{}-{}-{}", yesteryear, 12, 31);//年统计截止日
            DateTime parse = DateUtil.parse(endtimeStr, "yyyy-MM-dd");
            // 判断是否以已经生成记录 && 判断当前时间是否大于往年结束时间
            log.info("往年结束时间："+ DateUtil.endOfYear(dateTime));
            log.info("往年时间比较："+ DateUtil.between(DateUtil.endOfYear(dateTime), new Date(), DateUnit.MS, false));
            if(CollUtil.isEmpty(intactRatelist) && DateUtil.between(DateUtil.endOfYear(dateTime), new Date(), DateUnit.MS, false) > 0){
                IntactRatioDto dto = new IntactRatioDto().setYear(yesteryear).setStartMonth(1).setEndMonth(12);
                List<IntactRatioVo> whllist = ADOConnection.runTask(dbstr, intactratioservice, "intactRatioDetails", List.class, dto);//获取相依的设备完好率
                IntactRatioVo gshj = whllist.stream().filter(w -> w.getDeptName().equals("公司合计")).findFirst().orElse(new IntactRatioVo());
                if (gshj.getYearItems() != null) {
                    IntactRateBean extracted = extracted(yesteryear, endtimeStr, gshj.getYearItems().getIntactRate(), 4, 12);
                    mapper.insertSelective(extracted);
                }
            }
        }
    }

    // 半年平均设备完好率（废弃）
    @Deprecated
    private void halfayearDeprecated(SessionFactory factory, String dbstr) {
        IntactRateBeanMapper mapper = factory.getMapper(IntactRateBeanMapper.class);
        int noewYear = DateUtil.year(new Date());

        //查今年 半年的 月平均设备完好率
        List<IntactRateBean> intactRatelist = factory.getMapper(IntactRateBeanMapper.class).queryByYearAndQuarter(noewYear, 2);
        if (CollUtil.isEmpty(intactRatelist)) {
            String endtimeStr = StrUtil.format("{}-{}-{}", noewYear, "06", 30);//半年统计截止日
            DateTime parse = DateUtil.parse(endtimeStr, "yyyy-MM-dd");
            // 判断是否以已经生成记录 && 判断当前时间是否大于6月最后一天结束时间
            log.info("半年结束时间："+ DateUtil.endOfMonth(parse));
            log.info("半年时间比较："+DateUtil.between(DateUtil.endOfMonth(parse), new Date(), DateUnit.MS, false));
            if(CollUtil.isEmpty(intactRatelist) && DateUtil.between(DateUtil.endOfMonth(parse), new Date(), DateUnit.MS, false) > 0){
                IntactRatioDto dto = new IntactRatioDto().setYear(noewYear).setStartMonth(1).setEndMonth(12);
                List<IntactRatioVo> whllist = ADOConnection.runTask(dbstr, intactratioservice, "intactRatioDetails", List.class, dto);//获取相依的设备完好率
                IntactRatioVo gshj = whllist.stream().filter(w -> w.getDeptName().equals("公司合计")).findFirst().orElse(new IntactRatioVo());
                if (CollUtil.isNotEmpty(gshj.getQuarterItems())) {
                    List<IntacQuotaDetVo> quarterItems = gshj.getQuarterItems().subList(0,2);
                    BigDecimal reduce = quarterItems.stream().map(IntacQuotaDetVo::getIntactRate).reduce(BigDecimal.ZERO, BigDecimal::add);
                    reduce = reduce.divide(new BigDecimal(quarterItems.size()), 2, BigDecimal.ROUND_DOWN);
                    IntactRateBean extracted = extracted(noewYear, endtimeStr, reduce, 2, 6);
                    mapper.insertSelective(extracted);
                }
            }
        }
    }

    // 半年平均设备完好率
    private void halfayear(SessionFactory factory, String dbstr) {
        IntactRateBeanMapper mapper = factory.getMapper(IntactRateBeanMapper.class);
        int noewYear = DateUtil.year(new Date());

        //查今年 半年的 月平均设备完好率
        List<IntactRateBean> intactRatelist = factory.getMapper(IntactRateBeanMapper.class).queryByYearAndQuarter(noewYear, 2);
        if (CollUtil.isEmpty(intactRatelist)) {
            String endtimeStr = StrUtil.format("{}-{}-{}", noewYear, "06", 30);//半年统计截止日
            DateTime parse = DateUtil.parse(endtimeStr, "yyyy-MM-dd");
            // 判断是否以已经生成记录 && 判断当前时间是否大于6月最后一天结束时间
            log.info("半年结束时间："+ DateUtil.endOfMonth(parse));
            log.info("半年时间比较："+DateUtil.between(DateUtil.endOfMonth(parse), new Date(), DateUnit.MS, false));
            if(CollUtil.isEmpty(intactRatelist) && DateUtil.between(DateUtil.endOfMonth(parse), new Date(), DateUnit.MS, false) > 0){
                IntactRatioDto dto = new IntactRatioDto().setYear(noewYear).setStartMonth(1).setEndMonth(12);
                List<IntactRatioVo> whllist = ADOConnection.runTask(dbstr, intactratioservice, "intactRatioDetails", List.class, dto);//获取相依的设备完好率
                IntactRatioVo gshj = whllist.stream().filter(w -> w.getDeptName().equals("公司合计")).findFirst().orElse(new IntactRatioVo());
                if (gshj.getHalfYearItems() != null) {
                    IntactRateBean extracted = extracted(noewYear, endtimeStr, gshj.getHalfYearItems().getIntactRate(), 2, 6);
                    mapper.insertSelective(extracted);
                }
            }
        }
    }

    /**
     * 构建指标数据
     * @param year          年
     * @param endtimeStr
     * @param intactRate
     * @param quarter
     * @param month
     */
    private IntactRateBean extracted(int year, String endtimeStr, BigDecimal intactRate, Integer quarter, Integer month) {
        IntactRateBean intactRateBean = new IntactRateBean();
        intactRateBean.setId(CodeTools.getCode32());
        intactRateBean.setCode("7805");
        intactRateBean.setCodeName("机组完好率");
        intactRateBean.setOrgCode("000001");
        intactRateBean.setOrgName("测试水司");
        intactRateBean.setIntactRate(StrUtil.format("{}%", intactRate));//往年设备完好率
        intactRateBean.setFrequency("halfyearcum");
        intactRateBean.setBillDate(endtimeStr);
        intactRateBean.setYear(year);
        intactRateBean.setMonth(month);
        intactRateBean.setDay(31);
        intactRateBean.setQuarter(quarter);
        intactRateBean.setSpare1(StrUtil.format("{}Q{}", year, quarter));
        intactRateBean.setSpare2(StrUtil.format("{}-{}", year, month<10?"0"+month:month));
        intactRateBean.setDeleteFlag(false);
        intactRateBean.setCreateTime(new Date());
        intactRateBean.setUpdateTime(new Date());
        intactRateBean.setDataSources("生产信息管理系统");
        return intactRateBean;
    }


}
